﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace TileBoard.WebParts.TileBoard
{
    class Toolpart : Microsoft.SharePoint.WebPartPages.ToolPart
    {
        private TileBoard webPart;
        Label lblListToDisplay;
        protected HiddenField hdnListIdentifier { get; set; }
        Table tblFieldNames;
        Panel toolPartPanel;
        Button btnList;
        DropDownList ddlFrontText, ddlHyperlink, ddlPicture, ddlBackText, ddlColor;
        private string strID;

        private SPList itemList = null;

        protected TextBox txtListTitle { get; set; }

        public Toolpart()
        {
            this.txtListTitle = new TextBox();
            this.hdnListIdentifier = new HiddenField();
        }

        protected override void CreateChildControls()
        {
            //try
            //{
                this.webPart = (TileBoard)this.ParentToolPane.SelectedWebPart;

                lblListToDisplay = new Label();
                lblListToDisplay.Text = "List:";

                toolPartPanel = new Panel();

                this.txtListTitle.ID = "txtEntityPath";
                this.txtListTitle.CssClass = "UserInput";
                this.txtListTitle.Style.Add("margin", "4px 0 0 0");

                btnList = new Button();
                btnList.CssClass = "UserButton";
                btnList.OnClientClick = String.Format("LaunchPickerTreeDialog('CbqPickerSelectListTitle','CbqPickerSelectListText','{0}','', '{1}', null,'','','/_layouts/images/smt_icon.gif','', callback, ''); return false;", "listsOnly", SPContext.Current.Web.Url);
                btnList.Text = "...";

                toolPartPanel.Controls.Add(lblListToDisplay);
                toolPartPanel.Controls.Add(new LiteralControl("<br />"));

                toolPartPanel.Controls.Add(txtListTitle);
                toolPartPanel.Controls.Add(btnList);
                toolPartPanel.Controls.Add(new LiteralControl("<br />"));

                toolPartPanel.Controls.Add(hdnListIdentifier);

                ddlBackText = new DropDownList();
                ddlColor = new DropDownList();
                ddlFrontText = new DropDownList();
                ddlHyperlink = new DropDownList();
                ddlPicture = new DropDownList();  

                tblFieldNames = new Table();                
                TableRow row = new TableRow();
                TableCell cell = new TableCell();
                row.Cells.Add(cell);
                
                tblFieldNames.Rows.Add(row);
                toolPartPanel.Controls.Add(tblFieldNames);
                toolPartPanel.Controls.Add(new LiteralControl("<br />"));

                Controls.Add(toolPartPanel);

                base.CreateChildControls();
            //}
            //catch { }
        }

        protected SPList GetList(string identifier)
        {
            if (identifier != null && identifier.StartsWith("SPList"))
            {
               // try
                //{
                    string[] segments = identifier.TrimEnd(':').Split('?');
                    string listID = segments[0].Substring(7);
                    string webID = segments[1].Substring(6);
                    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb web = site.OpenWeb(new Guid(webID)))
                        {
                            // Search for list with specified URL 
                            foreach (SPList list in web.Lists)
                            {
                                if (list.ID == new Guid(listID))
                                    return list;
                            }
                        }
                    }
                /*}
                catch (Exception)
                {
                    return null;
                }*/
            }

            return null;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            EnsureChildControls();

            /*try
            {*/
                // Get currently selected list
                string identifier = null;
                if (!String.IsNullOrEmpty(this.hdnListIdentifier.Value))
                    identifier = this.hdnListIdentifier.Value;
                else if (this.webPart.ListId != Guid.Empty && this.webPart.ListWebId != Guid.Empty)
                    identifier = String.Format("SPList:{0}?SPWeb:{1}:", this.webPart.ListId, this.webPart.ListWebId);                

                itemList = this.GetList(identifier);
                
                if (itemList != null)
                {
                    this.BuildFieldNameControls();
                }
            /*}
            catch { }*/
        }

        private void BuildFieldNameHeader()
        {
            TableHeaderRow hRow = new TableHeaderRow();

            TableHeaderCell hCellField = new TableHeaderCell();
            hCellField.Style.Add("text-align", "left");
            hCellField.Text = SPContext.Current.Web.Url.ToLower().Contains("/fra/") ? "Paramètre" : "Parameter";
            hRow.Cells.Add(hCellField);

            TableHeaderCell hCellTitle = new TableHeaderCell();
            hCellTitle.Style.Add("text-align", "left");
            hCellTitle.Text = SPContext.Current.Web.Url.ToLower().Contains("/fra/") ? "Champ associé" : "Associated Field";
            hRow.Cells.Add(hCellTitle);
            
            tblFieldNames.Rows.Add(hRow);
        }

        private void BuildFieldNameControls()
        {
            tblFieldNames.Rows.Clear();
            this.BuildFieldNameHeader();

            LoadFields();
            foreach (string field in this.webPart.FieldNames)
            {
                ddlBackText.Items.Add(field);
                ddlColor.Items.Add(field);
                ddlFrontText.Items.Add(field);
                ddlHyperlink.Items.Add(field);
                ddlPicture.Items.Add(field);
            }
            ddlColor.Items.Add("[Random]");
            ddlBackText.Items.Add("[None]");

            TableRow row = new TableRow();

            TableCell cellCaption = new TableCell();
            cellCaption.Text = "Front Text:";
            row.Cells.Add(cellCaption);

            TableCell cellText = new TableCell();
            cellText.Controls.Add(ddlFrontText);
            row.Cells.Add(cellText);
             
            tblFieldNames.Rows.Add(row);

            row = new TableRow();

            cellCaption = new TableCell();
            cellCaption.Text = "Hyperlink:";
            row.Cells.Add(cellCaption);

            cellText = new TableCell();
            cellText.Controls.Add(ddlHyperlink);
            row.Cells.Add(cellText);

            tblFieldNames.Rows.Add(row);

            row = new TableRow();

            cellCaption = new TableCell();
            cellCaption.Text = "Picture:";
            row.Cells.Add(cellCaption);

            cellText = new TableCell();
            cellText.Controls.Add(ddlPicture);
            row.Cells.Add(cellText);

            tblFieldNames.Rows.Add(row);

            row = new TableRow();

            cellCaption = new TableCell();
            cellCaption.Text = "Back Text:";
            row.Cells.Add(cellCaption);

            cellText = new TableCell();
            cellText.Controls.Add(ddlBackText);
            row.Cells.Add(cellText);

            tblFieldNames.Rows.Add(row);

            row = new TableRow();

            cellCaption = new TableCell();
            cellCaption.Text = "Color:";
            row.Cells.Add(cellCaption);

            cellText = new TableCell();
            cellText.Controls.Add(ddlColor);
            row.Cells.Add(cellText);

            tblFieldNames.Rows.Add(row);
        }

        private Control FindControlRecursive(Control root, string id)
        {
            if (root.ID == id)
                return root;

            foreach (Control control in root.Controls)
            {
                Control childControl = FindControlRecursive(control, id);
                if (childControl != null)
                    return childControl;
            }

            return null;
        }

        public override void ApplyChanges()
        {
            LoadFields();
        }

        public void LoadFields()
        {
            string listId = this.hdnListIdentifier.Value;
            if (string.IsNullOrEmpty(listId) && !string.IsNullOrEmpty(this.webPart.ListId.ToString()))
                listId = String.Format("SPList:{0}?SPWeb:{1}:", this.webPart.ListId, this.webPart.ListWebId);  
            itemList = this.GetList(listId);

            // Save custom properties 
            this.webPart.ListId = itemList.ID;
            this.webPart.ListWebId = itemList.ParentWeb.ID;
            if (ddlFrontText.SelectedItem != null)
                this.webPart._fieldFrontText = ddlFrontText.SelectedItem.Text;
            if (ddlHyperlink.SelectedItem != null)
                this.webPart._fieldHyperlink = ddlHyperlink.SelectedItem.Text;
            if (ddlPicture.SelectedItem != null)
                this.webPart._fieldPicture = ddlPicture.SelectedItem.Text;
            if (ddlBackText.SelectedItem != null)
                this.webPart._fieldBackText = ddlBackText.SelectedItem.Text;
            if (ddlColor.SelectedItem != null)
                this.webPart._fieldColor = ddlColor.SelectedItem.Text;

            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb(this.webPart.ListWebId))
                {
                    SPList selList = web.Lists[this.webPart.ListId];
                    if (selList != null)
                    {
                        this.webPart.FieldNames.Clear();
                        foreach (SPField field in selList.Fields)
                        {
                            if (!field.ReadOnlyField && !field.Hidden)
                            {
                                this.webPart.FieldNames.Add(field.InternalName);
                            }
                        }
                    }
                }
            }
        }

        public override void SyncChanges()
        {
            if (this.webPart != null)
            {
                this.itemList = this.GetList(this.hdnListIdentifier.Value);
                if (this.itemList != null)
                {
                    this.hdnListIdentifier.Value = this.strID;
                    this.txtListTitle.Text = this.itemList.Title;                    
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            EnsureChildControls();

            /*try
            {*/
                if (!String.IsNullOrEmpty(this.hdnListIdentifier.Value))
                    this.strID = this.hdnListIdentifier.Value;
                else if (!this.webPart.ListId.Equals(Guid.Empty))
                    this.strID = String.Format("SPList:{0}?SPWeb:{1}:", this.webPart.ListId.ToString(), this.webPart.ListWebId.ToString());

                // Retrieve SPList if list identifier exists 
                if (!String.IsNullOrEmpty(this.strID))
                    this.itemList = this.GetList(this.strID);

                // Set default field values 
                if (this.itemList != null)
                    this.txtListTitle.Text = this.itemList.Title;
                this.hdnListIdentifier.Value = this.strID;

                if(ddlFrontText.SelectedItem != null)
                    SelectItem(ref ddlFrontText,this.webPart.FrontText);
                if(ddlHyperlink.SelectedItem != null)
                    SelectItem(ref ddlHyperlink, this.webPart.Hyperlink);
                if(ddlPicture.SelectedItem !=null)
                    SelectItem(ref ddlPicture, this.webPart.Picture);
                if(ddlBackText.SelectedItem != null)
                    SelectItem(ref ddlBackText, this.webPart.BackText);
                if(ddlColor.SelectedItem != null)
                    SelectItem(ref ddlColor, this.webPart.Color);

                // Load PickerTreeDialog.js
                this.Controls.Add(new LiteralControl("<script type=\"text/javascript\" src=\"/_layouts/1033/PickerTreeDialog.js\"></script>"));

                // Render the JavaScript PickerTreeDialog callback
                StringBuilder script = new StringBuilder();
                script.Append("<script type=\"text/javascript\">");
                script.Append("callback = function(arr){");
                script.Append("if(arr != null && arr != undefined){");
                script.Append("document.getElementById('" + this.hdnListIdentifier.ClientID + "').value=arr[0];");
                script.Append("document.getElementById('" + this.txtListTitle.ClientID + "').value=arr[2];");
                script.Append("__doPostBack('" + this.ClientID + "', arr[0]);");
                script.Append("}");
                script.Append("};");
                script.Append("</script>");
                this.Controls.Add(new LiteralControl(script.ToString()));
            /*}
            catch { }*/
        }

        private void SelectItem(ref DropDownList ddl, string selectedText)
        {
            int index = 0;
            foreach (ListItem li in ddl.Items)
            {
                if (li.Text == selectedText)
                {
                    ddl.SelectedIndex = index;
                    break;
                }
                index++;
            }
        }
    }
}
